#!/bin/bash

# 注册接口详细测试脚本

echo "=========================================="
echo "注册接口详细测试"
echo "=========================================="
echo ""

# 获取服务器地址
if [ -z "$1" ]; then
    BASE_URL="http://localhost:8088"
else
    BASE_URL="$1"
fi

echo "测试地址: $BASE_URL"
echo ""

# 测试1：基础健康检查
echo "1️⃣ 测试服务是否可访问"
echo "----------------------------------------"
curl -s -o /dev/null -w "状态码: %{http_code}\n" "$BASE_URL/api/index"
echo ""

# 测试2：正确的注册请求（详细模式）
echo "2️⃣ 测试正确的注册请求（带详细输出）"
echo "----------------------------------------"
echo "请求URL: POST $BASE_URL/api/auth/register"
echo '请求Body: {"phone":"13900000999","password":"123456","nickname":"测试用户"}'
echo ""
echo "响应内容："
curl -X POST "$BASE_URL/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{"phone":"13900000999","password":"123456","nickname":"测试用户"}' \
  -w "\n\n状态码: %{http_code}\n响应时间: %{time_total}s\n" \
  -v 2>&1 | grep -E "< HTTP|< Content-Type|{.*}|状态码|响应时间"
echo ""
echo ""

# 测试3：查看完整的请求和响应
echo "3️⃣ 完整请求响应（包含所有header）"
echo "----------------------------------------"
curl -X POST "$BASE_URL/api/auth/register" \
  -H "Content-Type: application/json" \
  -d '{"phone":"13900000888","password":"123456"}' \
  -i 2>&1
echo ""
echo ""

# 测试4：测试CORS
echo "4️⃣ 测试CORS（跨域）配置"
echo "----------------------------------------"
curl -X OPTIONS "$BASE_URL/api/auth/register" \
  -H "Origin: http://example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Content-Type" \
  -v 2>&1 | grep -E "< HTTP|< Access-Control"
echo ""
echo ""

# 测试5：错误的Content-Type
echo "5️⃣ 测试错误的Content-Type（看是否会返回400）"
echo "----------------------------------------"
curl -X POST "$BASE_URL/api/auth/register" \
  -H "Content-Type: text/plain" \
  -d '{"phone":"13900000777","password":"123456"}' \
  -w "\n状态码: %{http_code}\n"
echo ""
echo ""

# 测试6：测试其他正常接口
echo "6️⃣ 测试其他公开接口作为对比"
echo "----------------------------------------"
echo "测试 GET /api/banner/list:"
curl -s -o /dev/null -w "状态码: %{http_code}\n" "$BASE_URL/api/banner/list"
echo ""
echo "测试 POST /api/auth/login:"
curl -s -X POST "$BASE_URL/api/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"phone":"13900000999","password":"123456"}' \
  -o /dev/null -w "状态码: %{http_code}\n"
echo ""
echo ""

# 测试7：查看后端日志
echo "7️⃣ 查看最近的后端日志"
echo "----------------------------------------"
if [ -f "/var/log/weiqi-backend.log" ]; then
    echo "最近5条日志:"
    tail -n 5 /var/log/weiqi-backend.log
else
    echo "日志文件不存在，尝试systemd日志:"
    journalctl -u weiqi-backend -n 5 --no-pager 2>/dev/null || echo "无法获取日志"
fi
echo ""

echo "=========================================="
echo "测试完成"
echo "=========================================="
echo ""
echo "如果看到400错误，请注意："
echo "1. 检查响应body中的具体错误信息"
echo "2. 确认Content-Type是否正确"
echo "3. 确认请求body是否是有效的JSON"
echo "4. 查看后端日志中的错误信息"


